package rsj.service.user;

import com.alibaba.fastjson.JSON;
import com.rlyy.aibase.utils.base.MapNode;
import com.rlyy.aibase.utils.base.Node;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import rsj.api.user.entity.UserAccount;
import rsj.db.dbutils.UniqueID;
import rsj.service.UserInfoService;
import rsj.sql.user.UserDao;

import java.time.LocalDateTime;

/**
 * 用户
 *
 * @author yuanqinglong
 * @since 2021/7/16 14:42
 */
@Service
public class UserServiceImpl implements IUserService {


    @Autowired
    private UserDao userDao;


    /**
     * 添加用户
     *
     * @param userAccount 用户帐户
     */
    @Override
    public UserAccount addUser(UserAccount userAccount) {
        userAccount.setUserId(String.valueOf(UniqueID.generateId()));
        userAccount.setUserPassword(UserInfoService.stringToMD5(userAccount.getUserPassword()));
        userAccount.setUserCtime(LocalDateTime.now());
        userAccount.setUserUtime(LocalDateTime.now());
        userDao.addUser(userAccount);
        return userAccount;
    }


    /**
     * 更新用户密码
     *
     * @param userAccount 用户帐户
     */
    @Override
    public void updateUserPassword(UserAccount userAccount) {
        if (StringUtils.isNotBlank(userAccount.getUserPassword())) {
            userAccount.setUserPassword(UserInfoService.stringToMD5(userAccount.getUserPassword()));
            userDao.updateUserPassword(userAccount);
        }
    }

    /**
     * 得到用户帐户
     *
     * @param orgId org id
     * @return {@link UserAccount}
     */
    @Override
    public UserAccount getUserAccount(String orgId) {
        MapNode mapNode = userDao.getUser(orgId);
        return JSON.parseObject(JSON.toJSONString(mapNode.toMap()), UserAccount.class);
    }

    /**
     * 得到合同用户状态
     *
     * @param orgpId 合同id
     * @return {@link String}
     */
    @Override
    public String getContractUserStatus(String orgpId) {
        Node contractUserStatus = userDao.getContractUserStatus(orgpId);
        return contractUserStatus.value();
    }

    /**
     * 获取用户信息
     *
     * @param userId 用户id
     * @return {@link String}
     */
    @Override
    public UserAccount getUserInfo(String userId) {
        MapNode mapNode = userDao.queryBaseInfoByUser(userId);
        return JSON.parseObject(JSON.toJSONString(mapNode.toMap()), UserAccount.class);
    }
}
